import React, { useMemo, useState, useEffect } from 'react';
import {
  Modal,
  View,
  Text,
  StyleSheet,
  Pressable,
  ScrollView,
  TextInput,
  Platform,
  Keyboard,
  Dimensions,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { COLORS } from '../styles/constants';

const DEFAULT_CITIES = [
  '上海',
  '北京',
  '广州',
  '深圳',
  '杭州',
  '成都',
  '西安',
  '重庆',
];

export default function CityPickerModal({
  visible,
  onClose,
  onSelect,
  cities = DEFAULT_CITIES,
}) {
  // === State Hooks ===
  const [searchText, setSearchText] = useState('');
  const [keyboardHeight, setKeyboardHeight] = useState(0);

  // === Effect Hooks ===
  // 监听Modal打开/关闭和键盘状态
  useEffect(() => {
    if (!visible) {
      setSearchText('');
      setKeyboardHeight(0);
      return;
    }

    const showSubscription = Keyboard.addListener(
      Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',
      e => {
        setKeyboardHeight(e.endCoordinates.height);
      },
    );
    const hideSubscription = Keyboard.addListener(
      Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide',
      () => {
        setKeyboardHeight(0);
      },
    );

    return () => {
      showSubscription.remove();
      hideSubscription.remove();
    };
  }, [visible, cities]);

  // 统一处理城市数据格式：支持字符串数组和对象数组
  const cityItems = useMemo(() => {
    // 确保 cities 是数组
    if (!Array.isArray(cities)) {
      return DEFAULT_CITIES.map(cityName => ({
        key: cityName,
        displayName: cityName,
        data: cityName,
      }));
    }

    if (cities.length === 0) {
      return DEFAULT_CITIES.map(cityName => ({
        key: cityName,
        displayName: cityName,
        data: cityName,
      }));
    }


    return cities.map((city, index) => {
      if (typeof city === 'string') {
        // 字符串格式
        return {
          key: city,
          displayName: city,
          data: city,
        };
      } else if (city && typeof city === 'object') {
        // 对象格式，支持多种可能的字段名
        const cityName = city.cityName || city.name || city.city || '未知城市';
        return {
          key:
            city.id ||
            city.adcode ||
            city.cityCode ||
            city.code ||
            cityName + '_' + index,
          displayName: cityName,
          data: city, // 传递完整的城市对象
        };
      } else {
        // 异常数据，使用索引作为key
        console.warn('[CityPickerModal] 城市数据格式异常:', city);
        return {
          key: 'unknown_' + index,
          displayName: '未知城市',
          data: city,
        };
      }
    });
  }, [cities]);

  // 根据搜索文本过滤城市
  const filteredCities = useMemo(() => {
    if (!searchText.trim()) {
      return cityItems;
    }

    const lowerSearchText = searchText.toLowerCase().trim();
    return cityItems.filter(item =>
      item.displayName.toLowerCase().includes(lowerSearchText),
    );
  }, [cityItems, searchText]);

  // 处理城市选择
  const handleCitySelect = cityData => {
    setSearchText(''); // 清空搜索框
    onSelect?.(cityData);
  };

  // 处理关闭
  const handleClose = () => {
    setSearchText(''); // 清空搜索框
    onClose();
  };

  // 计算弹窗高度：显式像素，避免百分比不生效
  const windowHeight = Dimensions.get('window').height;
  const sheetHeight = useMemo(() => {
    const TARGET = 600; // 目标高度（像素）
    if (keyboardHeight > 0) {
      if (Platform.OS === 'ios') {
        // iOS：留出更少空间，让弹窗更高，避免被输入法完全遮挡
        const safeSpace = Math.max(keyboardHeight - 100, 80); // 减少安全间距
        const available = windowHeight - safeSpace;
        // iOS最小450，最大550
        return Math.max(450, Math.min(550, available));
      } else {
        // Android：保持原有逻辑
        const safeSpace = keyboardHeight + 60;
        const available = windowHeight - safeSpace;
        return Math.max(350, Math.min(450, available));
      }
    }
    // 无键盘：固定600，不超过可用高度
    return Math.min(TARGET, windowHeight - 80);
  }, [keyboardHeight, windowHeight]);

  return (
    <Modal
      visible={visible}
      animationType="slide"
      transparent
      onRequestClose={handleClose}
    >
      <Pressable style={styles.backdrop} onPress={handleClose}>
        <View style={styles.container}>
          <Pressable
            style={[styles.sheet, { height: sheetHeight }]}
            onPress={e => e.stopPropagation()}
          >
            <View style={styles.header}>
              <Text style={styles.title}>选择城市</Text>
              <Pressable onPress={handleClose} hitSlop={8}>
                <Text style={styles.close}>关闭</Text>
              </Pressable>
            </View>

            {/* 搜索框 */}
            <View style={styles.searchContainer}>
              <Icon
                name="search-outline"
                size={20}
                color={COLORS.text.placeholder}
                style={styles.searchIcon}
              />
              <TextInput
                style={styles.searchInput}
                placeholder="搜索城市名称"
                placeholderTextColor={COLORS.text.placeholder}
                value={searchText}
                onChangeText={setSearchText}
                autoCapitalize="none"
                autoCorrect={false}
                returnKeyType="search"
                blurOnSubmit={true}
              />
              {searchText.length > 0 && (
                <Pressable onPress={() => setSearchText('')} hitSlop={8}>
                  <Icon name="close-circle" size={20} color={COLORS.text.placeholder} />
                </Pressable>
              )}
            </View>

            {/* 城市列表 */}
            <ScrollView
              style={styles.scrollView}
              contentContainerStyle={styles.list}
              showsVerticalScrollIndicator={true}
              keyboardShouldPersistTaps="handled"
              keyboardDismissMode="on-drag"
            >
              {filteredCities.length > 0 ? (
                filteredCities.map(item => (
                  <Pressable
                    key={item.key}
                    style={styles.item}
                    onPress={() => handleCitySelect(item.data)}
                  >
                    <Text style={styles.itemText}>{item.displayName}</Text>
                  </Pressable>
                ))
              ) : (
                <View style={styles.emptyContainer}>
                  <Icon name="search-outline" size={48} color={COLORS.text.disabled} />
                  <Text style={styles.emptyText}>未找到匹配的城市</Text>
                  <Text style={styles.emptyHint}>请尝试其他关键词</Text>
                </View>
              )}
            </ScrollView>
          </Pressable>
        </View>
      </Pressable>
    </Modal>
  );
}

const styles = StyleSheet.create({
  backdrop: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.35)',
    justifyContent: 'flex-end',
  },
  container: {
    flex: 1,
    width: '100%',
    justifyContent: 'flex-end',
  },
  sheet: {
    backgroundColor: COLORS.white,
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
    overflow: 'hidden',
  },
  scrollView: {
    flex: 1,
    maxHeight: '100%',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: COLORS.border.light,
  },
  title: { fontSize: 16, fontWeight: '600', color: COLORS.text.primary },
  close: { color: COLORS.primary, fontSize: 15 },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: COLORS.background.secondary,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: COLORS.border.light,
  },
  searchIcon: {
    marginRight: 8,
  },
  searchInput: {
    flex: 1,
    height: 40,
    backgroundColor: COLORS.white,
    borderRadius: 8,
    paddingHorizontal: 12,
    fontSize: 15,
    color: COLORS.text.secondary,
  },
  list: {
    paddingHorizontal: 16,
    paddingTop: 8,
    paddingBottom: 24,
  },
  item: {
    paddingVertical: 14,
    paddingHorizontal: 4,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: COLORS.border.light,
  },
  itemText: {
    fontSize: 15,
    color: COLORS.text.primary,
  },
  emptyContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 16,
    color: COLORS.text.tertiary,
    marginTop: 12,
    fontWeight: '500',
  },
  emptyHint: {
    fontSize: 14,
    color: COLORS.text.placeholder,
    marginTop: 8,
  },
});
